package five;

import javax.management.MBeanOperationInfo;
import javax.management.MBeanParameterInfo;
import javax.management.modelmbean.ModelMBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanInfo;
import javax.management.modelmbean.ModelMBeanInfoSupport;
import javax.management.modelmbean.ModelMBeanOperationInfo;
import javax.management.modelmbean.RequiredModelMBean;

/**
 * ModelMBeanUtils 主要是返回一个RequiredModelMBean类，
 * 此类主要包括了一个ModelMBeanInfo类的信息。在 ModelMBeanInfo中定义了所有对需要管理的属性和方法的描述
 *
 */
public class ModelMBeanUtils {
	
	private static final boolean READABLE = true;
	private static final boolean WRITABLE = true;
	private static final boolean BOOLEAN = true;
	private static final String STRING_CLASS = "java.lang.String";

	public static RequiredModelMBean createModelerMBean() {
		RequiredModelMBean model = null;
		try {
			model = new RequiredModelMBean();
			model.setManagedResource(new Hello(), "ObjectReference");
			ModelMBeanInfo info = createModelMBeanInfo();
			model.setModelMBeanInfo(info);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return model;
	}

	private static ModelMBeanInfo createModelMBeanInfo() {
		//构造name属性信息
		ModelMBeanAttributeInfo nameAttrInfo = new ModelMBeanAttributeInfo(
				"Name",//属性名
				STRING_CLASS,//属性类型
				"people name",//描述
				READABLE,WRITABLE,!BOOLEAN,//读写
				null//说明
		);
		
		//构造方法sayHello()操作的信息
		ModelMBeanOperationInfo sayHello1Info = new ModelMBeanOperationInfo(
				"sayHello",
				null,//说明
				null,//参数
				"void",
				MBeanOperationInfo.INFO,
				null
		);
		
		//构造一个有参数的sayHello
		MBeanParameterInfo[] param2 = new MBeanParameterInfo[1];
		param2[0] = new MBeanParameterInfo("whoName", STRING_CLASS, "say hello to who");
		ModelMBeanOperationInfo sayHello2Info = new ModelMBeanOperationInfo(
			"sayHello",
			null,
			param2,
			"void",
			MBeanOperationInfo.INFO,
			null
		);
		
		ModelMBeanInfo mbeanInfo = new ModelMBeanInfoSupport(
				RequiredModelMBean.class.getName(),//MBean类
				null,//描述
				new ModelMBeanAttributeInfo[]{nameAttrInfo}, //所有的属性信息，这里只有一个属性
				null,//所有的构造函数，这里没有
				new ModelMBeanOperationInfo[]{sayHello1Info,sayHello2Info},//所有的操作信息
				null,//所有的通知信息， 这里没有
				null //
		);
		
		return mbeanInfo;
	}

}
